package Advanced.fixedLength;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class fixedLengthServer {
    public static void main(String[] args) throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(new NioEventLoopGroup(1),new NioEventLoopGroup(2));
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                log.debug("server connect......");
                super.channelActive(ctx);
            }

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                // 固定接受长度为8个字节
                pipeline.addLast(new FixedLengthFrameDecoder(8));

                // 添加出入站日志
                pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                log.debug("server disconnect......");
                super.channelInactive(ctx);
            }

        }).bind(8080).sync();
    }
}
